package creatingDBs;

import java.io.*;
import java.util.Scanner;

import java.sql.*;

import Logging.Monitor;

public class DBCreator {
	
	///////////////////////////// CONSTANT MEMBERS ////////////////////////////
	public enum objectType{Like, Comment, Post};
	// JDBC driver name and database URL
   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";  
   static final String DB_URL = "jdbc:mysql://localhost/";
	
   // Database credentials
   static final String USER = "root";
   static final String PASS = "";
   
   // Database schemes
   static final String main_db_scheme = "fan_page_name VARCHAR(256), " +
   										"user_id VARCHAR(256), " +
   										"user_name VARCHAR(256), " +
   										"type_of_obj ENUM('post','comment','like'), " +
   										"obj_text VARCHAR(256), " +
   										"obj_id VARCHAR(256)";
   
   /////////////////////////// CONSTANT MEMBERS - END //////////////////////////
   
   //////////////////////////////// CONSTRUCTORS ///////////////////////////////
   
   public DBCreator() {
	   
	   Connection con = null;
	   Statement stmt = null;
	   
	   try{
			// Register JDBC driver
			Class.forName("com.mysql.jdbc.Driver");

			// Open a connection
			con = DriverManager.getConnection(DB_URL, USER, PASS);
			Monitor.write(this, "Connected to the database");
			
			// Creating the Security database space
			stmt = con.createStatement();
			String sql = "CREATE DATABASE IF NOT EXISTS SECURITY";
			stmt.executeUpdate(sql);
			Monitor.write(this, "Created the SECURITY database space");
			
	   	} catch (ClassNotFoundException e) {
	   		Monitor.write(this, "Driver not found");
		} catch (SQLException e) {
			Monitor.write(this, "database access error occured "+e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Throwable ignore) {
				Monitor.write(this, "Cannot close the connection properly "+ignore.getMessage());
			}
		}
   }
   
   ///////////////////////////// CONSTRUCTORS - END ////////////////////////////
   
   
   /**
    * This method receives a scheme string and builds an SQL string for creating
    * a table. 
    * @param dbName the name of our created table
    * @param dbScheme a String that represents the scheme part definition of the
    * table creation SQL clause
    * @return a String that creates the specified table
    */
   private String createTableString(String dbName, String dbScheme) {
	   
	   String creation = 	"CREATE TABLE IF NOT EXISTS " 
		   					+ "SECURITY"+"."+dbName + " ( " + dbScheme + " )";
	   return creation;
   }
   
	/**
	 * This method scans the main DB text file and creates a main_db table.
	 * The method populates the table with the read records.
	 * @param fileName the name of the main DB file to read 
	 * @param dbTable the name of our database 
	 * @throws FileNotFoundException 
	 * @throws SQLException 
	 */
	public void createMainDB(String fileName, String dbTable) throws FileNotFoundException, SQLException {
		
		Connection con = null;
		Statement stmt = null;
		
		Monitor.write(this, "======Entered createMainDB======");
		try{
			// Register JDBC driver
			Class.forName("com.mysql.jdbc.Driver");

			// Open a connection
			con = DriverManager.getConnection(DB_URL, USER, PASS);
			Monitor.write(this, "Connected to the database");
			
			// Creating the main_db table
			String createTable = createTableString(dbTable,main_db_scheme);
			stmt = con.createStatement();
			Monitor.write(this, "Using this scheme for the creation " +createTable );
			stmt.executeUpdate(createTable);
			Monitor.write(this, "Created our empty main_db. We now go and populate it");
			
			// Populating the main_db
			//TODO implement
		}
		 catch (ClassNotFoundException e) {
			Monitor.write(this, "Driver not found "+e.getMessage());
		} catch (SQLException e) {
			Monitor.write(this, "database access error occured "+e.getMessage());
		} finally {
			try {
				con.close();
			} catch (Throwable ignore) {
				Monitor.write(this, "Cannot close the connection properly "+ignore.getMessage());
			}
	
		}
	}
	
	// Reading the file main_db.txt
	/*public void readAndWrite(String flePath, String dbName)  {
		
		/**
		 * This class encapsulates the action we perform for each line we read
		 * @author ron
		 *
		 *
		class PerformAction {
			
			void action() {
				
			}
			
		}

		File fFile = new File(flePath); 
	  	boolean first = true;
	  
	  	// Note that FileReader is used, not File, since File is not Closeable
	  	Scanner scanner;
		try {
			scanner = new Scanner(new FileReader(fFile));
			
			// Fetching a record from the db and performing the action on it
			
			
		} catch (FileNotFoundException e) {
			Monitor.writeException(e);
		}
		
		try {
	      //first use a Scanner to get each line
	      while (scanner.hasNextLine())
	      {
	        processLine( scanner.nextLine(), dbName, first );
	        first = false;
	      }
		} finally {
	      scanner.close();
	    }
	  }
	
	  protected void processLine(String aLine, String dbName, boolean first) throws SQLException, InstantiationException, IllegalAccessException, ClassNotFoundException{
	    
		  
		
		int length1 = "<fan_page_name>".length();
		if (first == true)
		{
			length1 = length1 +3;
		}
		int length2 = "<user_id>".length();
		int length3 = "<user_name>".length();
		int length4 = "<type_of_obj>".length();
		int length5 = "<obj_text>".length();
		int length6 = "<obj_id>".length();
	
		//use a second Scanner to parse the content of each line   
		Scanner scanner = new Scanner(aLine);
	    scanner.useDelimiter("<=//>");
	    if ( scanner.hasNext() ){
	  	
	      String fanPageName = scanner.next();
	      fanPageName = fanPageName.substring(length1, fanPageName.length());
	      String userId  = scanner.next();
	      userId = userId.substring(length2, userId.length());
	      String userName = scanner.next();
	      userName = userName.substring(length3, userName.length());
	      String objectType = scanner.next();
	      objectType = objectType.substring(length4, objectType.length());
	      String objectText = scanner.next();
	      if (objectText.length() > length5)
	      {
	      objectText = objectText.substring(length5, objectText.length());
	      }
	      else objectText = null;
	      
	      
	      String objectId = scanner.next();
	      objectId = objectId.substring(length6, objectId.length());
	      
	    System.out.println(fanPageName);
	    System.out.println(userId);
	    System.out.println(userName);
	    System.out.println(objectType);
	    System.out.println(objectText);
	    System.out.println(objectId);
	    
	    
	    
	    Connection con = null;  
	    Class.forName("com.mysql.jdbc.Driver").newInstance();
		con = DriverManager.getConnection(DB_URL, USER, PASS);
		Statement stmt = con.createStatement();
			
		stmt.executeUpdate("INSERT INTO dbName VALUES(fanPageName,userId, userName,objectType,objectText,objectId) ");
		 Monitor.write(this, "writing the fields " + userId + userName );
	    }
	    else {
	    	Monitor.write(this, "Line is empty");
	    }
	  }*/
	  
}
